package com.cetcs.kmga.dataManager.service.impl.dataManager;

import com.alibaba.druid.sql.visitor.functions.Left;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cetc.cloud.kmga.util.MqUtil;
import com.cetcs.kmga.common.Data;
import com.cetcs.kmga.common.DateUtil;
import com.cetcs.kmga.common.Page;
import com.cetcs.kmga.dataManager.dao.mybatis.*;
import com.cetcs.kmga.dataManager.entity.dataManager.ClientLimit;
import com.cetcs.kmga.dataManager.entity.dataManager.DataResourceCode;
import com.cetcs.kmga.dataManager.entity.dataManager.Resrc;
import com.cetcs.kmga.dataManager.entity.dataManager.ResrcAuditObj;
import com.cetcs.kmga.dataManager.entity.dataManager.vo.*;
import com.cetcs.kmga.dataManager.entity.device.DeviceInfo;
import com.cetcs.kmga.dataManager.entity.device.SecuRule;

import com.cetcs.kmga.dataManager.entity.device.vo.KeyAndValueVo;
import com.cetcs.kmga.dataManager.entity.global.AuditMqMessage;
import com.cetcs.kmga.dataManager.entity.global.AuditRuleMqMessage;
import com.cetcs.kmga.dataManager.entity.global.DeviceMqMessage;
import com.cetcs.kmga.dataManager.global.DataManagerConstants;
import com.cetcs.kmga.dataManager.schedule.InitCdTypeListener;
import com.cetcs.kmga.dataManager.service.dataManager.DataManagerService;
import com.cetcs.kmga.dataManager.util.CommonUtils;
import com.cetcs.kmga.dataManager.util.MqParamsUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import deviceservice.core.DevManager;
import deviceservice.entity.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/** 数据监管
 * Created by yyangs on 2017/2/14.
 */
@Service
public class DataManagerServiceImpl implements DataManagerService {
    private static Log LOGGER = LogFactory.getLog(DataManagerServiceImpl.class);


    @Autowired
    private AuditManagerMapper auditManagerMapper;
    @Autowired
    private CodeTableManagerMapper codeTableManagerMapper;
    @Autowired
    private SecuRuleMapper secuRuleMapper;
    @Autowired
    private DeviceManagerMapper deviceManagerMapper;
    @Autowired
    private InitCdTypeListener initCdTypeListener;
    @Autowired
    private DataManagerMapper dataManagerMapper;


    /**
     * 获取数据源列表
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public ResourceTreeVo getDataResourceList(Data dataMap) throws Exception {
        ResourceTreeVo resourceTreeVo = new ResourceTreeVo();
        //将所有的资源 查询出来
        List<ResourceTreeDataBaseVo> dataBases = Lists.newArrayList();
        List<Resrc> resrcs = auditManagerMapper.getAllResrcByCondition(dataMap);
        // 然后根据类型分类在每个类型中
        Map<Integer, List<Resrc>> map = new LinkedHashMap<Integer, List<Resrc>>();
        CommonUtils.listGroup2Map(resrcs, map, Resrc.class, "getResrcTypeCode");// 输入方法名
        for(Map.Entry<Integer,List<Resrc>> mapObject:map.entrySet()){
            ResourceTreeDataBaseVo resourceTreeDataBaseVo = new ResourceTreeDataBaseVo();
            resourceTreeDataBaseVo.setId("A"+String.valueOf(mapObject.getKey()));
            //通过id查询码表 类型
            Data codeParams = new Data();
            codeParams.put("code",mapObject.getKey());
            List<DataResourceCode> codeAndValues = codeTableManagerMapper.getAllResourceTypeByCondition(codeParams);
            if(codeAndValues.get(0).getIsUsable()==0){
                //如果未启用就跳过
                continue;
            }
            resourceTreeDataBaseVo.setName(codeAndValues.get(0).getValue());
            List<ResourceTreeDataTableVo> resourceTreeDataTableVos = Lists.newArrayList();
            for(Resrc resrc:mapObject.getValue()) {
                ResourceTreeDataTableVo resourceTreeDataTableVo = new ResourceTreeDataTableVo();
                resourceTreeDataTableVo.setId("B"+String.valueOf(resrc.getId()));
                resourceTreeDataTableVo.setTable(resrc.getName());
                List<ResourceTreeDataObjectVo> resourceTreeDataObjectVos = Lists.newArrayList();
                Data params = new Data();
                // 然后将审计对象封装起来
                params.put("resrcId",resrc.getId());
                List<ResrcAuditObj> resrcAuditObjs = auditManagerMapper.getAllResrcAuditObjByCondition(params);
                for(ResrcAuditObj resrcAuditObj:resrcAuditObjs){
                    ResourceTreeDataObjectVo resourceTreeDataObjectVo = new ResourceTreeDataObjectVo();
                    resourceTreeDataObjectVo.setId("C"+String.valueOf(resrcAuditObj.getId()));
                    if(resrcAuditObj.getAlias()!=null){
                        resourceTreeDataObjectVo.setName(resrcAuditObj.getAlias());
                    }else{
                        resourceTreeDataObjectVo.setName(resrcAuditObj.getName());
                    }
                    resourceTreeDataObjectVos.add(resourceTreeDataObjectVo);
                }
                resourceTreeDataTableVo.setChild(resourceTreeDataObjectVos);
                resourceTreeDataTableVos.add(resourceTreeDataTableVo);
            }
            resourceTreeDataBaseVo.setItem(resourceTreeDataTableVos);
            dataBases.add(resourceTreeDataBaseVo);
        }
        resourceTreeVo.setDatabaseS(dataBases);
        // 最后封装未知对象
        ResourceTreeDataUnkownVo unknown = new ResourceTreeDataUnkownVo();
        unknown.setId("Aunknown");
        unknown.setName("unknown");
        List<ResourceTreeDataObjectVo> resourceTreeDataObjectVos = Lists.newArrayList();
        Data params = new Data();
        // 然后将审计对象封装起来
        params.put("unknown",1);
        List<ResrcAuditObj> resrcAuditObjs = auditManagerMapper.getAllResrcAuditObjByCondition(params);
        for(ResrcAuditObj resrcAuditObj:resrcAuditObjs){
            ResourceTreeDataObjectVo resourceTreeDataObjectVo = new ResourceTreeDataObjectVo();
            resourceTreeDataObjectVo.setId("A"+String.valueOf(resrcAuditObj.getId()));
            if(resrcAuditObj.getAlias()!=null){
                resourceTreeDataObjectVo.setName(resrcAuditObj.getAlias());
            }else{
                resourceTreeDataObjectVo.setName(resrcAuditObj.getName());
            }
            resourceTreeDataObjectVos.add(resourceTreeDataObjectVo);
        }
        unknown.setItem(resourceTreeDataObjectVos);
        resourceTreeVo.setUnknown(unknown);
        return resourceTreeVo;
    }


    /**
     * 查询资源列表
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public List<Resrc> getResourceLists(Data dataMap) throws Exception {
        //获得资源列表
        List<Resrc> resrcList = auditManagerMapper.getAllResrcByCondition(dataMap);
        return resrcList;
    }

    /**
     * 同步数据源
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public ResourceTreeVo synchronizeDataResource(Data dataMap) throws Exception {
        //获取所有的设备信息 然后 每个设备获取其审计接口数据
        Data params = new Data();
        List<DeviceInfo> deviceInfos = deviceManagerMapper.getDeviceInfosByCondition(params);
        String nowDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Integer result = 0;

        /**
         * 获取到所有的资源列表
         */
        List<ResrcAuditObj> resrcAuditObjs = auditManagerMapper.getAllResrcAuditObjByCondition(params);
        //新增的资源列表
        List<ResrcAuditObj> resrcAuditObjsAdd = Lists.newArrayList();
        //修改的资源列表
        List<ResrcAuditObj> resrcAuditObjsUpdate = Lists.newArrayList();
        //删除的资源列表
        List<ResrcAuditObj> resrcAuditObjsDel = Lists.newArrayList();
        LOGGER.info("===========开始同步===========");
        //循环调用接口 获取数据
        for(DeviceInfo deviceInfo:deviceInfos){
            List<Object> dataSources = Lists.newArrayList();
            try {
                String flag = "运维设备".equals(deviceInfo.getType())? DataManagerConstants.APPLICATION_FORM_URLENCODED:DataManagerConstants.APPLICATION_JSON;
                dataSources = DevManager.query(flag,deviceInfo.getUrl(), deviceInfo.getToken(), deviceInfo.getId(), "datasource");
            }catch (Exception e){
                //e.printStackTrace();
                LOGGER.info(deviceInfo.getName() + "同步失败");
                continue;
            }
            //根据 数据库名称和版本号 查询审计类型
            for(Object object:dataSources){
                DataSource dataSource = (DataSource)object;
                //根据获取到的审计信息 ip 端口 来源 判断是否已经存在
                params.clear();
                ResrcAuditObj temp = new ResrcAuditObj();
                temp.setServerIp(dataSource.getIpString());
                temp.setPort(dataSource.getPort());
                switch (deviceInfo.getType()) {
                    case "探针设备":
                        temp.setSrc(0);
                        break;
                    case "脱敏设备":
                        temp.setSrc(1);
                        break;
                    case "运维设备":
                        temp.setSrc(2);
                        break;
                    default:
                        throw new Exception("数据库数据出错！");
                }
//                params.put("serverIp",dataSource.getIpString());
//                params.put("port",dataSource.getPort());
//                switch (deviceInfo.getType()){
//                    case "探针设备":params.put("src",0);break;
//                    case "脱敏设备":params.put("src",1);break;
//                    case "运维设备":params.put("src",2);break;
//                    default:throw new Exception("数据库数据出错！");
//                }

                //可以找到当前的数据库中已经有的东西
                List<ResrcAuditObj> objs = resrcAuditObjs.stream().filter(p->temp.equals(p)).collect(Collectors.toList());
                if(objs.size()>0) {
                    //表示当前数据库中包含该资源
                    ResrcAuditObj resrcAuditObj = objs.get(0);
                    if(dataSource.getAuditObjName()!=null) {
                        resrcAuditObj.setName(dataSource.getAuditObjName());
                    }
                    if(dataSource.getDbType()!=null) {
                        resrcAuditObj.setType(dataSource.getDbType());
                    }
                    resrcAuditObj.setGetTime(nowDateTime);
                    resrcAuditObjsUpdate.add(resrcAuditObj);
                }else{
                    ResrcAuditObj resrcAuditObj = new ResrcAuditObj();
                    resrcAuditObj.setServerIp(dataSource.getIpString().trim());
                    resrcAuditObj.setPort(dataSource.getPort());
                    resrcAuditObj.setSrc(temp.getSrc());
                    resrcAuditObj.setGetTime(nowDateTime);
                    if(dataSource.getAuditObjName()!=null) {
                        resrcAuditObj.setName(dataSource.getAuditObjName());
                        resrcAuditObj.setAlias(dataSource.getAuditObjName());
                    }
                    if(dataSource.getDbType()!=null) {
                        resrcAuditObj.setType(dataSource.getDbType());
                    }
                    resrcAuditObjsAdd.add(resrcAuditObj);
                }



                /*  之前写的通过查询数据库的
                List<ResrcAuditObj> resrcAuditObjs = auditManagerMapper.getAllResrcAuditObjByCondition(params);
                if(resrcAuditObjs != null && resrcAuditObjs.size() > 0){
                    // 已经存在修改更新时间 名称 类型
                    Data resourceParams = new Data();
                    resourceParams.put("id",resrcAuditObjs.get(0).getId());
                    if(dataSource.getAuditObjName()!=null) {
                        resourceParams.put("name", dataSource.getAuditObjName());
                    }
                    if(dataSource.getDbType()!=null) {
                        resourceParams.put("type", dataSource.getDbType());
                    }
                    resourceParams.put("getTime", nowDateTime);
                    result += auditManagerMapper.updateResrcAuditObj(resourceParams);
                }else{
                    // 不存在加入未知对象中
                    if(dataSource.getAuditObjName()!=null) {
                        params.put("name", dataSource.getAuditObjName());
                        params.put("alias", dataSource.getAuditObjName());
                    }
                    if(dataSource.getDbType()!=null) {
                        params.put("type", dataSource.getDbType());
                    }
                    params.put("getTime", nowDateTime);
                    result += auditManagerMapper.createResrcAuditObj(params);
                }*/
            }
        }
        /**
         * 找到 未匹配到的资源审计对象
         */
        resrcAuditObjsDel = resrcAuditObjs;
        resrcAuditObjsDel.removeAll(resrcAuditObjsAdd);
        resrcAuditObjsDel.removeAll(resrcAuditObjsUpdate);

        /**
         * 这里在进行批量的新增、修改、删除
         //封装 发送MQ
         // 如果 添加成功 写入MQ队列
         */
        if(resrcAuditObjsAdd.size()>0) {
            result += auditManagerMapper.batchAddResrcAuditObj(resrcAuditObjsAdd);
            //发送新增mq
            AuditMqMessage auditMqMessage = new AuditMqMessage();
            auditMqMessage.setAuditObjId(resrcAuditObjsAdd.stream().map(p->String.valueOf(p.getId())).collect(Collectors.toList()));
            auditMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            auditMqMessage.setType("AuditObjAdd");
            MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditMqMessage));

        }
        if(resrcAuditObjsUpdate.size()>0) {
            result += auditManagerMapper.batchUpdateResrcAuditObj(resrcAuditObjsUpdate);
            //发送更新mq
            AuditMqMessage auditMqMessage = new AuditMqMessage();
            auditMqMessage.setAuditObjId(resrcAuditObjsUpdate.stream().map(p->String.valueOf(p.getId())).collect(Collectors.toList()));
            auditMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            auditMqMessage.setType("AuditObjMod");
           MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditMqMessage));

        }
        if(resrcAuditObjsDel.size()>0) {
            result += auditManagerMapper.batchDelResrcAuditObj(resrcAuditObjsDel);
            //发送删除mq
            AuditMqMessage auditMqMessage = new AuditMqMessage();
            auditMqMessage.setAuditObjId(resrcAuditObjsDel.stream().map(p->String.valueOf(p.getId())).collect(Collectors.toList()));
            auditMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            auditMqMessage.setType("AuditObjDel");
           MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditMqMessage));

        }
//        params.clear();
//        params.put("getTime", nowDateTime);
//        //删除时间在当前时间之前的所有数据
//        result += auditManagerMapper.deleteResrcAuditObj(params);
        //重新查询树结构
        params.clear();
        LOGGER.info("===========结束同步===========");
        ResourceTreeVo resourceTreeVo = getDataResourceList(params);
        initCdTypeListener.reloadResourceIn2CodeTb();
        return resourceTreeVo;
    }

    /**
     * 获得审计对象信息
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public AuditObjectConfigVo getAuditObjectById(Data dataMap) throws Exception {
        AuditObjectConfigVo auditObjectConfigVo = new AuditObjectConfigVo();
        //先获得该审计信息
        ResrcAuditObj resrcAuditObj = auditManagerMapper.getResrcAuditObjById(dataMap);
        auditObjectConfigVo.setId(String.valueOf(resrcAuditObj.getId()));
        if(resrcAuditObj.getRemark()!=null && !"".equals(resrcAuditObj.getRemark())) {
            auditObjectConfigVo.setName(resrcAuditObj.getRemark());
        }else{
            auditObjectConfigVo.setName(resrcAuditObj.getName());
        }
        auditObjectConfigVo.setIp(resrcAuditObj.getServerIp());
        auditObjectConfigVo.setPort(String.valueOf(resrcAuditObj.getPort()));
        if(resrcAuditObj.getAlias()!=null) {
            auditObjectConfigVo.setAliases(resrcAuditObj.getAlias());
        }
        if(resrcAuditObj.getRemark()!=null){
            auditObjectConfigVo.setText(resrcAuditObj.getRemark());
        }
        switch (resrcAuditObj.getSrc()){
            case 0: auditObjectConfigVo.setFrom("探针");break;
            case 1: auditObjectConfigVo.setFrom("脱敏");break;
            case 2: auditObjectConfigVo.setFrom("堡垒机");break;
            //代表类型错误
            default:break;
        }
        //获得审计资源的树
        //先获得 所有的数据源 然后分组
        Data params = new Data();
        List<Resrc> resrcs = auditManagerMapper.getAllResrcByCondition(params);
        // 然后根据类型分类在每个类型中
        Map<Integer, List<Resrc>> map = new LinkedHashMap<Integer, List<Resrc>>();
        CommonUtils.listGroup2Map(resrcs, map, Resrc.class, "getResrcTypeCode");// 输入方法名
        //封装
        List<AuditObjectConfigTreeVo> auditObjectConfigTreeVos = Lists.newArrayList();
        boolean isopen = false;
        for(Map.Entry<Integer, List<Resrc>> entry:map.entrySet()){
            AuditObjectConfigTreeVo auditObjectConfigTreeVo = new AuditObjectConfigTreeVo();
            //这个是数据源 需要去码表查询
            auditObjectConfigTreeVo.setpId("0");
            auditObjectConfigTreeVo.setNocheck(true);Data codeParams = new Data();
            codeParams.put("code",entry.getKey());
            List<DataResourceCode> codeAndValues = codeTableManagerMapper.getAllResourceTypeByCondition(codeParams);
            if(codeAndValues.get(0).getIsUsable()==0){
                //如果未启用 就跳过本次循环
                continue;
            }
            auditObjectConfigTreeVo.setName(codeAndValues.get(0).getValue());
            auditObjectConfigTreeVo.setId("A"+String.valueOf(entry.getKey()));
//            auditObjectConfigTreeVo.setOpen(false);
            isopen = false;
            for(Resrc resrc:entry.getValue()){
                AuditObjectConfigTreeVo auditObjectConfigTreechildrenVo = new AuditObjectConfigTreeVo();
                auditObjectConfigTreechildrenVo.setpId("A"+String.valueOf(entry.getKey()));
                auditObjectConfigTreechildrenVo.setNocheck(false);
                auditObjectConfigTreechildrenVo.setName(resrc.getName());
                auditObjectConfigTreechildrenVo.setId("B"+String.valueOf(resrc.getId()));
                auditObjectConfigTreechildrenVo.setOpen(false);
                if(resrcAuditObj.getResrcId()!=null && resrcAuditObj.getResrcId().compareTo(resrc.getId()) == 0) {
                    auditObjectConfigTreechildrenVo.setChecked(true);
                    isopen = true;
                }else{
                    auditObjectConfigTreechildrenVo.setChecked(false);
                }

                auditObjectConfigTreeVos.add(auditObjectConfigTreechildrenVo);
            }
            auditObjectConfigTreeVo.setOpen(isopen);
            auditObjectConfigTreeVos.add(auditObjectConfigTreeVo);
        }
        auditObjectConfigVo.setTree(auditObjectConfigTreeVos);
        return auditObjectConfigVo;
    }

    /**
     * 配置审计对象信息
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer configureAuditObject(Data dataMap) throws Exception {
        //修改审计信息
        //现需要查询信息是否正确
        Integer result = 0;
        if("unknown".equals(dataMap.get("resrcId"))){
            dataMap.put("unknown",1);
            dataMap.remove("resrcId");
        }
        result = auditManagerMapper.updateResrcAuditObj(dataMap);
        if(result>0){
            initCdTypeListener.reloadResourceIn2CodeTb();
        }
        /**
         * yyangs mq消息 审计对象修改
         */
        AuditMqMessage auditMqMessage = new AuditMqMessage();
        List<String> list = Lists.newArrayList();
        list.add(String.valueOf(dataMap.get("resrcId")));
        auditMqMessage.setAuditObjId(list);
        auditMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        auditMqMessage.setType("AuditObjMod");
        MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditMqMessage));

        return result;
    }

    /**
     * 根据ID查询资源信息
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public ResourceVo getResourceById(Data dataMap) throws Exception {
        Resrc resrc = auditManagerMapper.getResrcById(dataMap);
        ResourceVo resourceVo = new ResourceVo();
        if(resrc!=null) {
            resourceVo.setId("A" + String.valueOf(resrc.getId()));
            resourceVo.setName(resrc.getName());
            resourceVo.setEdition(resrc.getVers());
            resourceVo.setResourcesGrade(resrc.getSupevLevel());
            resourceVo.setText(resrc.getDesc());
            resourceVo.setIp(resrc.getServerIp());
        }
        return resourceVo;
    }

    /**
     * 新增或者更新 资源
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer saveOrUpdataResource(Data dataMap) throws Exception {
        Integer result = 0;
        //判断id的首字母  如果是A表示 新增  B表示 更新
        if(dataMap.getString("id").startsWith("A")){
            dataMap.put("resrcTypeCode",dataMap.getString("id").substring(1));
            dataMap.remove("id");
            result = auditManagerMapper.createResrc(dataMap);
        }else{
            dataMap.put("id",dataMap.getString("id").substring(1));
            result = auditManagerMapper.updateResrc(dataMap);
        }
        if(result>0){
            initCdTypeListener.reloadResourceIn2CodeTb();
        }
        return result;
    }

    /**
     * 删除数据源
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer deleteResource(Data dataMap) throws Exception {
        Integer result = 0;
        result = auditManagerMapper.deleteResrc(dataMap);
        if(result>0){
            initCdTypeListener.reloadResourceIn2CodeTb();
        }
        return result;
    }

    /**
     * 根据资源id 获取安全规则列表分页
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Page getSecuRuleByResourceId(Data dataMap) throws Exception {
        List<SecuRule> secuRules = secuRuleMapper.getSecuRuleInfosByCondition(dataMap, new PageBounds(dataMap.getInt("page"), dataMap.getInt("pageSize")));
        PageList<SecuRule> pageList = (PageList<SecuRule>) secuRules;
        Page page = new Page(pageList);
        List<SecuRuleVo> secuRuleVos = Lists.newArrayList();
        for( Object object:page.getContent()){
            SecuRule secuRule = (SecuRule) object;
            SecuRuleVo secuRuleVo = new SecuRuleVo();
            secuRuleVo.setId(secuRule.getId());
            secuRuleVo.setAlarmName(secuRule.getName());
            secuRuleVo.setRisk(secuRule.getLevel());
            if(secuRule.getUpdateTime().contains(".")) {
                secuRuleVo.setTime(secuRule.getUpdateTime().split("\\.")[0]);
            }else{
                secuRuleVo.setTime(secuRule.getUpdateTime());
            }
            secuRuleVo.setRunningType(Integer.parseInt(secuRule.getStat()));
            secuRuleVos.add(secuRuleVo);
        }
        page.setContent(secuRuleVos);
        return page;
    }

    /**
     * 判断资源是否已存在
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer isExitForResource(Data dataMap) throws Exception {
        List<Resrc> resrcs = auditManagerMapper.getAllResrcByCondition(dataMap);
        return resrcs.size();
    }

    /**
     * 判断审计对象是否已经存在
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer isExitForAuditObject(Data dataMap) throws Exception {
        List<ResrcAuditObj> resrcAuditObjs = auditManagerMapper.getAllResrcAuditObjByCondition(dataMap);
        return resrcAuditObjs.size();

    }

    /**
     * 跟新告警规则 根据规则ID
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateSecuRule(Data dataMap) throws Exception {
        Integer result = secuRuleMapper.updateSecuRule(dataMap);
        return result;
    }

    /**
     * 获取 添加 资源类型
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public List<ResrcTypeVo> getAndAddResourceType(Data dataMap) throws Exception {
        List<ResrcTypeVo> resrcTypeVos = Lists.newArrayList();
        List<DataResourceCode> dataResourceCodes = codeTableManagerMapper.getAllResourceTypeByCondition(new Data());
        Map<String,ResrcTypeVo> map = Maps.newHashMap();
        for(DataResourceCode dataResourceCode:dataResourceCodes){
            ResrcTypeVo resrcTypeVo = new ResrcTypeVo();
            resrcTypeVo.setId("A"+dataResourceCode.getCode());
            resrcTypeVo.setName(dataResourceCode.getValue());
            resrcTypeVo.setChecked(0);
            map.put(resrcTypeVo.getId(),resrcTypeVo);
        }
        List<Resrc> resrcs = auditManagerMapper.getAllResrcByCondition(dataMap);
        // 然后根据类型分类在每个类型中
        Map<Integer, List<Resrc>> mapList = new LinkedHashMap<Integer, List<Resrc>>();
        CommonUtils.listGroup2Map(resrcs, mapList, Resrc.class, "getResrcTypeCode");// 输入方法名
        for (Map.Entry<Integer, List<Resrc>> mapObject : mapList.entrySet()) {
            if(mapObject.getKey()!=null){
                map.get("A"+mapObject.getKey()).setChecked(1);
            }
        }

        for(Map.Entry<String,ResrcTypeVo> entry:map.entrySet()){
            ResrcTypeVo resrcTypeVo = entry.getValue();
            resrcTypeVos.add(resrcTypeVo);
        }
        return resrcTypeVos;
    }


    //==================== zhangchunlin start ======================//
    @Override
    public List findSysUsers(String keyword){
        return secuRuleMapper.findSysUsers(keyword);
    }

    @Override
    public int saveSecuRuleByResourceId(SecuRuleAddVo vo){
        if(vo.getSecuRuleInfo().getId() != null && vo.getSecuRuleInfo().getId().intValue() >0){
            return modifySecuRuleByResourceId(vo);
        }
        //保存告警规则
        vo.getSecuRuleInfo().setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        secuRuleMapper.addSecuRule(vo.getSecuRuleInfo());
        saveySecuRuleDetail(vo);


        /**
         * yyangs mq消息 安全审计规则增加
         */
        AuditRuleMqMessage auditRuleMqMessage = new AuditRuleMqMessage();
        List<String> list = Lists.newArrayList();
        list.add(String.valueOf(vo.getSecuRuleInfo().getId()));
        auditRuleMqMessage.setAuditRuleId(list);
        auditRuleMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        auditRuleMqMessage.setType("AuditRuleAdd");
        MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditRuleMqMessage));

        return 1;
    }

    /**
     * 修改告警规则
     */
    private int modifySecuRuleByResourceId(SecuRuleAddVo vo){
        String id = String.valueOf(vo.getSecuRuleInfo().getId());
        secuRuleMapper.removeSecuRuleConditionByRuleId("sdp_busi_secu_rule_cond",id);
        secuRuleMapper.removeSecuRuleConditionByRuleId("sdp_busi_secu_rule_step",id);


        //保存告警规则
        vo.getSecuRuleInfo().setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        secuRuleMapper.modifySecuRule(vo.getSecuRuleInfo());
        saveySecuRuleDetail(vo);


        /**
         * yyangs mq消息 安全审计规则修改
         */
        AuditRuleMqMessage auditRuleMqMessage = new AuditRuleMqMessage();
        List<String> list = Lists.newArrayList();
        list.add(String.valueOf(vo.getSecuRuleInfo().getId()));
        auditRuleMqMessage.setAuditRuleId(list);
        auditRuleMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        auditRuleMqMessage.setType("AuditRuleMod");
        MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditRuleMqMessage));
        return 1;
    }

    /**
     * 保存告警规则相关信息,告警条件,设置步骤等
     */
    private void saveySecuRuleDetail(SecuRuleAddVo vo){
        //保存告警条件
        if(vo.getAlertConditions() != null && vo.getAlertConditions().size()>0){
            for(SecuRuleAlertCondition condition : vo.getAlertConditions()){
                condition.setRuleId(vo.getSecuRuleInfo().getId());
            }
            secuRuleMapper.addSecuRuleCondition(vo.getAlertConditions());
        }
        //保存设置步骤
        if(!StringUtils.isEmpty(vo.getInfo())){
            secuRuleMapper.addSecuRuleStepInfo(vo.getSecuRuleInfo().getId(),vo.getInfo());
        }
    }
    @Override
    public JSONObject findSecuRuleById(String id){
        JSONObject ret = new JSONObject();

        List<SecuRuleAlertCondition> conditions = secuRuleMapper.findSecuRuleCondition(id);
        ret.put("alertConditions",conditions);
        String stepInfo = secuRuleMapper.findSecuRuleStepByRuleId(id);
        ret.put("info",stepInfo);

        SecuRule rule = secuRuleMapper.findSecuRuleById(id);
        JSONObject jo = (JSONObject)JSONObject.toJSON(rule);
        //替换SecuRule.receiver，如果email存在数据库中就换成对应的userId,不存在就临时生成一个ID,组成{"id":"","text":""}结构
       int index = 1;
        Set<Object> receiverList = new HashSet<>();
        if(!StringUtils.isEmpty(rule.getReceiver())){
            String[] receiverArray = rule.getReceiver().split(",");
            for(String receiver : receiverArray){
                if(StringUtils.isEmpty(receiver)){continue;}
                String userId = secuRuleMapper.findUserIdByEmail(receiver);
                if(userId != null){
                    if(userId.indexOf(",") > 0){
                        receiverList.add(userId.split(",")[0]);
                    }else{
                        receiverList.add(userId);
                    }
                }else{
                    Map<String,String> item = new HashMap<>();
                    item.put("id","N" +  index++);
                    item.put("text" , receiver);
                    receiverList.add(item);
                }
            }
        }
        jo.put("receiver" , receiverList);
        ret.put("secuRuleInfo",jo);
        return ret;
    }

    @Override
    public int removeSecuRuleById(String id){
        //删除告警条件
        secuRuleMapper.removeSecuRuleConditionByRuleId("sdp_busi_secu_rule_cond",id);
        secuRuleMapper.removeSecuRuleConditionByRuleId("sdp_busi_secu_rule_step",id);
        Integer result =  secuRuleMapper.removeSecuRuleById(id);
        if(result>0){


            /**
             * yyangs mq消息 安全审计规则删除
             */
            AuditRuleMqMessage auditRuleMqMessage = new AuditRuleMqMessage();
            List<String> list = Lists.newArrayList();
            list.add(id);
            auditRuleMqMessage.setAuditRuleId(list);
            auditRuleMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            auditRuleMqMessage.setType("AuditRuleDel");
            MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditRuleMqMessage));
        }
        return result;
    }

    @Override
    public int batchRemoveSecuRule(List<String> ids){
        if(ids == null || ids.size() == 0 ) return 1;
        for(String id : ids){
            removeSecuRuleById(id);
        }

        /**
         * yyangs mq消息 安全审计规则
         */
        AuditRuleMqMessage auditRuleMqMessage = new AuditRuleMqMessage();
        auditRuleMqMessage.setAuditRuleId(ids);
        auditRuleMqMessage.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        auditRuleMqMessage.setType("AuditRuleDel");
        MqUtil.getInstance(MqParamsUtil.getMqHost(),MqParamsUtil.getMqUser(),MqParamsUtil.getMqPwd()).sendBroacastMsg2Exch("amq.fanout",JSON.toJSONString(auditRuleMqMessage));
        return 1;
    }
    //==================== zhangchunlin end ======================//

    //流量阈值设置//
    @Override
    public Page getClientLimitList(Data dataMap) throws Exception {
        List<ClientLimitVo> resultList = Lists.newArrayList();
        List<ClientLimit> list = dataManagerMapper.getClientLimitList(dataMap, new PageBounds(dataMap.getInt("page"), dataMap.getInt("pageSize")));
        PageList<ClientLimit> pageList = (PageList<ClientLimit>) list;

        int i=1;
        for (ClientLimit ClientLimit : list){
            ClientLimitVo vo = new ClientLimitVo();
            vo.setRisk_content(i);
            vo.setRisk_id(ClientLimit.getIp());
            vo.setRisk_ip(ClientLimit.getIp());
            vo.setRisk_name(ClientLimit.getName());
            if (ClientLimit.getIn_limit() != null){
                vo.setRisk_in(ClientLimit.getIn_limit().replace(",","~"));
            }
            if (ClientLimit.getOut_limit() != null){
                vo.setRisk_out(ClientLimit.getOut_limit().replace(",","~"));
            }
            i++;
            resultList.add(vo);
        }

        Page page = new Page(pageList);
        page.setContent(resultList);

        return page;
    }

    @Override
    public ClientLimitInfoVo getClientLimitInfoByIp(Data params) throws Exception {
        ClientLimit ClientLimit = dataManagerMapper.getClientLimitInfoByIp(params);
        ClientLimitInfoVo result = new ClientLimitInfoVo();
        result.setIp(ClientLimit.getIp());
        if (ClientLimit.getIn_limit() != null){
            result.setInLeft(ClientLimit.getIn_limit().split(",")[0]);
            if (!ClientLimit.getIn_limit().split(",")[1].equals("MAX")){
                result.setInRight(ClientLimit.getIn_limit().split(",")[1]);
            }
        }
        if (ClientLimit.getOut_limit() != null){
            result.setOutLeft(ClientLimit.getOut_limit().split(",")[0]);
            if (!ClientLimit.getOut_limit().split(",")[1].equals("MAX")){
                result.setOutRight(ClientLimit.getOut_limit().split(",")[1]);
            }
        }

        return result;
    }

    @Override
    public int updateClientLimit(Data params) throws Exception {
        return dataManagerMapper.updateClientLimit(params);
    }

}
